package com.itheima.Demo04;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class DemoBS {
    public static void main(String[] args) {
        //创建服务器对象;
        try {
            ServerSocket ss = new ServerSocket(9090);
            while (true) {
                //接受浏览器的请求
                Socket s = ss.accept();
                //获取输入流
                InputStream is = s.getInputStream();
                //调用读取一行字符串的方法
                //readLine()
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String s1 = br.readLine();
                //从浏览器发过来的数据
                //System.out.println(str);   //  GET /1.jpg HTTP/1.1
                //1.截取用户要访问的资源名称
                System.out.println(s1);
                String[] arr = s1.split(" ");

                String name = arr[1];
                System.out.println(name);
                //2.查找文件是否存在
                File f = new File("Day18codes\\发车" + name);
                //3.获取输出流
                BufferedOutputStream os = new BufferedOutputStream(s.getOutputStream());
                if (f.exists()) {
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f) {
                    });
                    //要访问的资源存在
                    //如果存在把图片发送给浏览器
                    os.write("HTTP/1.1 200 OK\r\nContent-Type:image/jpeg\r\n\r\n".getBytes());
                    int i;
                    while ((i = bis.read()) != -1) {
                        os.write(i);
                    }

                    bis.close();
                } else {
                    os.write("HTTP/1.1 200 OK\r\nContent-Type:text/html;charset=UTF-8\r\n\r\n".getBytes());
                    os.write("访问不存在".getBytes());


                }
                os.close();
                s.close();
            }
        } catch (Exception e) {

        }
    }
}
